<template>
  <div class="wrap">
    <div class="wid_1820">
      <div class="header">
        <p class="app">
          <span>
            <!-- 2022-05-21 &emsp;&emsp;<span>21:21</span> -->
            {{ currentTime }}
          </span>
        </p>
        <p>
          <span class="hefont" onclick="toindex()">证券分时数据监控系统</span>
        </p>
      </div>

      <div class="content">
        <div class="tb tb_left">
          <h3>板块资金流</h3>
          <table class="table1">
            <tr class="tb_title">
              <td>板块名称</td>
              <td>当日涨跌幅</td>
            </tr>
            <tr
              v-for="(item, index) in industrys.issurge
                ? industrys.decline
                : industrys.surge"
              :key="index"
            >
              <td>{{ item.plateName }}</td>
              <td style="color: rgb(60, 203, 244)">
                {{ item.plateWave }}
                <span
                  :class="{
                    green: item.plateWave.indexOf('-') >= 0,
                    red: !item.plateWave.indexOf('-') >= 0,
                  }"
                  >{{ item.plateWave.indexOf("-") >= 0 ? "⬇" : "⬆" }}</span
                >
              </td>
            </tr>
          </table>
          <div class="indu">
            <div @click="induchang(0)" class="indubot">
              <img :src="!industrys.issurge ? img3 : img4" alt="" />
            </div>
            <div @click="induchang(1)" class="indubot">
              <img :src="!industrys.issurge ? img4 : img3" alt="" />
            </div>
          </div>
        </div>
        <div class="tb tb_middle">
          <h3>新股上市日历</h3>
          <table class="table1">
            <tr class="tb_title">
              <td>证券简称</td>
              <td>发行时间</td>
              <td>上市时间</td>
            </tr>
            <tr v-for="(item, index) in newstock" :key="index">
              <td>{{ item.stockName }}</td>
              <td style="color: rgb(60, 203, 244)">{{ item.issueDate }}</td>
              <td style="color: rgb(60, 203, 244)">{{ item.listingDate }}</td>
            </tr>
          </table>
          <div class="pagin">
            <div @click="pagechange(newstockpage, -1, 'newstock')" class="prep">
              上一页
            </div>
            <div @click="pagechange(newstockpage, 1, 'newstock')" class="next">
              下一页
            </div>
          </div>
        </div>
        <div style="clear: both"></div>
        <div class="tb tb_left1">
          <h3>港股通资金流</h3>
          <div style="display: inline-block" id="zjl"></div>
          <div class="jlr" style="width: 100%; height: 10%">
            <div style="margin-right: 5%" class="xxx">资金净流入:</div>
            <div
              :class="{
                xxx: true,
                xxx1: true,
              }"
            >
              {{ hscapital[0].netInflow }}
            </div>
            <div
              :class="{
                xxx: true,
                xxx1: true,
              }"
            >
              {{ hscapital[1].netInflow }}
            </div>
          </div>
        </div>
        <div class="tb tb_middle2">
          <h3>亚洲指数</h3>
          <table class="table1">
            <tr class="tb_title">
              <td>指数名称</td>
              <td>最新价</td>
            </tr>
            <tr v-for="(item, index) in indexs" :key="index">
              <td>{{ item.indexName }}</td>
              <td
                :class="{
                  green: item.fluctuationRange.indexOf('-') >= 0,
                  red: !item.fluctuationRange.indexOf('-') >= 0,
                }"
              >
                {{ item.latestPrice }}
              </td>
            </tr>
          </table>
          <div class="pagin">
            <div @click="pagechange(indexpage, -1, 'index')" class="prep">
              上一页
            </div>
            <div @click="pagechange(indexpage, 1, 'index')" class="next">
              下一页
            </div>
          </div>
        </div>
      </div>
      <div class="content2">
        <div class="tb tb_right">
          <h3 style="width: 50%; display: inline-block">
            证券快讯<span
              ><img
                @click="shuaxing()"
                class="shuaxing"
                style="width: 9%; padding-left: 10px"
                src="../assets/img/shuaxing.png"
                alt=""
            /></span>
          </h3>
          <div v-show="havenew" style="display: inline-block">
            <img
              style="width: 18%; display: inline-block"
              src="../assets/img/laba.png"
              alt=""
            />
            <div style="display: inline-block" class="xiaoxi">有新消息</div>
          </div>
          <div @scroll="scrollEvent" class="newlist">
            <div v-for="(item, index) in news" :key="index" class="new">
              <a target="_blank" class="newa" :href="item.link"
                ><div class="newtext">
                  <img
                    class="newimg"
                    :src="item.newsType == 'm_icon_3' ? img1 : img2"
                    alt=""
                  />【{{ item.title }}】 {{ item.description }}
                </div></a
              >
            </div>
            <div @click="more()" class="more">↓ ↓ 更 多</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      img1: require("../assets/img/text.png"),
      img2: require("../assets/img/bell.png"),
      img3: require("../assets/img/racle.png"),
      img4: require("../assets/img/racleac.png"),
      books: [],
      havenew: false,
      indexs: [
        {
          fluctuationRange: "0.23%",
          indexName: "上证指数",
          latestPrice: "3130.24",
        },
      ],
      indexpage: {
        page: 1,
        pageSize: 5,
      },
      hscapital: [
        {
          newInflow: "-12323",
        },
        {
          newInflow: "12323",
        },
      ],
      industrys: {
        surge: [],
        decline: [],
        issurge: true,
      },
      industrypage: {
        num: 5,
      },
      news: [],
      newpage: {
        page: 1,
        pageSize: 6,
        pernum: 6,
      },
      newstock: [],
      newstockpage: {
        page: 1,
        pageSize: 5,
      },
      socket: null,
      timer: "", //定义一个定时器的变量
      myChart: null,
      currentTime:
        new Date().getFullYear() +
        "-" +
        new Date().getMonth() +
        1 +
        "-" +
        new Date().getDate() +
        " " +
        new Date().getHours() +
        ":" +
        new Date().getMinutes() +
        ":" +
        new Date().getSeconds(), // 获取当前时间
    };
  },
  created() {
    (document.title = "师大实训group-5"), this.openSocket();
    var vm = this;
    vm.timer = setInterval(() => {
      var y = new Date().getFullYear();
      var m = vm.appendZero(new Date().getMonth() + 1);
      var d = vm.appendZero(new Date().getDate());
      var ho = vm.appendZero(new Date().getHours());
      var mi = vm.appendZero(new Date().getMinutes());
      var se = vm.appendZero(new Date().getSeconds());
      //修改数据date
      vm.currentTime = y + "-" + m + "-" + d + " " + ho + ":" + mi + ":" + se;
    }, 1000);
    this.getindex();
    this.getnews();
    this.getindustry();
    this.getnewstock();
    this.gethsCapital();
  },
  watch: {
    hscapital: {
      deep: true,
      handler: function () {
        this.getecharts();
      },
    },
  },
  mounted() {
    window.addEventListener('beforeunload', e => this.beforeunloadHandler(e))
    this.myChart = this.$echarts.init(document.getElementById("zjl"));
  },
  methods: {
    beforeunloadHandler(e) {
      if (this.socket != null) this.socket.close();
    },
    getecharts() {
      console.log("绘制资金流图");
      const option = {
        xAxis: [
          {
            type: "category",
            data: [this.hscapital[0].plateName, this.hscapital[1].plateName],
          },
          {
            type: "category",
            axisLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            splitArea: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            data: [this.hscapital[0].plateName, this.hscapital[1].plateName],
          },
        ],
        yAxis: {
          splitLine: {
            lineStyle: {
              color: ["#1F223C"],
            },
          },
          axisTick: {
            lineStyle: {
              width: 10,
            },
          },
        },
        tooltip: {
          // 鼠标悬浮提示框显示 X和Y 轴数据
          trigger: "axis",
          backgroundColor: "rgba(32, 33, 36,.7)",
          borderColor: "rgba(32, 33, 36,0.20)",
          borderWidth: 1,
          textStyle: {
            // 文字提示样式
            color: "#fff",
            fontSize: "12",
          },
          axisPointer: {
            // 坐标轴虚线
            type: "cross",
            label: {
              backgroundColor: "#6a7985",
            },
          },
        },
        series: [
          {
            name: "单日资金余额",
            type: "bar",
            data: [
              {
                value: this.hscapital[0].dayBalance,
                // 设置单个柱子的样式
                itemStyle: {
                  color: "#20A0FF",
                },
              },
              {
                value: this.hscapital[1].dayBalance,
                // 设置单个柱子的样式
                itemStyle: {
                  color: "#20A0FF",
                },
              },
            ],
            barWidth: "20%",
          },
          {
            /*这个bar是撑起横线的高度，并设置透明*/
            name: "资金限额",
            stack:
              "breakevenEleGroup" /*盈亏点数据组，需要设置才能将两个bar堆积在一起*/,
            type: "bar",
            xAxisIndex: 1,
            itemStyle: {
              normal: {
                color: "rgba(0,0,0,0)" /*设置bar为隐藏，撑起下面横线*/,
              },
            },
            data: [this.hscapital[0].dayLimit, this.hscapital[1].dayLimit],
          },
          {
            /*这个bar是横线的显示*/
            stack:
              "breakevenEleGroup" /*盈亏点数据组，需要设置才能将两个bar堆积在一起*/,
            type: "bar",
            xAxisIndex: 1,
            itemStyle: {
              normal: {
                color: "rgb(252,85,49)",
              },
            },
            data: [10, 10],
            barWidth: "20%",
          },
        ],
      };
      this.myChart.setOption(option);
      window.addEventListener("resize", () => {
        this.myChart.resize();
      });
    },
    getindex() {
      this.$axios
        .get(
          "/sdsx/index/" + this.indexpage.page + "/" + this.indexpage.pageSize
        )
        .then((res) => {
          console.log(res.data.data.list);
          this.indexs = res.data.data.list;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    gethsCapital() {
      this.$axios({
        url: "/sdsx/hsCapital",
        method: "POST",
        data: {
          plateName: "港股通",
        },
      })
        .then((res) => {
          console.log(res.data.data);
          let temp = JSON.parse(JSON.stringify(res.data.data));
          for (let i = 0; i < temp.length; i++) {
            let st = temp[i].dayBalance.substring(
              0,
              temp[i].dayBalance.length - 3
            );
            let st1 = temp[i].dayLimit.substring(
              0,
              temp[i].dayLimit.length - 3
            );
            temp[i].dayBalance = parseFloat(st);
            temp[i].dayLimit = parseFloat(st1);
          }
          console.log(temp);
          this.hscapital = temp;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getnewstock() {
      this.$axios
        .get(
          "/sdsx/newStock/" +
            this.newstockpage.page +
            "/" +
            this.newstockpage.pageSize
        )
        .then((res) => {
          console.log(res.data.data.list);
          this.newstock = res.data.data.list;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getindustry() {
      this.industrys = {
        surge: [],
        decline: [],
      };
      this.$axios
        .get("/sdsx/industry/" + this.industrypage.num)
        .then((res) => {
          console.log(res.data.data);
          let temp = res.data.data;
          for (let i = 0; i < temp.length; i++) {
            if (temp[i].plateWave.indexOf("-") >= 0)
              this.industrys.decline.push(temp[i]);
            else this.industrys.surge.push(temp[i]);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    getnews() {
      this.$axios
        .get("/sdsx/news/" + this.newpage.page + "/" + this.newpage.pageSize)
        .then((res) => {
          console.log(res.data.data);
          this.news = res.data.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    shuaxing() {
      this.newpage.pageSize = this.newpage.pernum;
      this.getnews();
      this.havenew = false;
    },
    openSocket() {
      console.log("正在链接socket");
      var socketUrl = "http://42.192.121.92:8088/sdsx/websocket/sdsx";
      socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
      if (this.socket != null) {
        console.log("关闭之前的socket");
        this.socket.close();
        this.socket = null;
      }
      this.socket = new WebSocket(socketUrl);
      //打开事件
      this.socket.onopen = () => {
        //获得消息事件
        console.log("socket已连接");
        this.socket.onmessage = (msg) => {
          console.log(msg);
          if (msg.data.indexOf("index") >= 0) {
            this.getindex();
            this.$message({
              duration: 1500,
              message: "中国指数已更新。",
              showClose: false,
              type: "success",
            });
          } else if (msg.data.indexOf("hsCapitals") >= 0) {
            this.gethsCapital();
            this.$message({
              title: "通知",
              duration: 1500,
              message: "港股通资金流已更新。",
              showClose: false,
              type: "success",
            });
          } else if (msg.data.indexOf("industry") >= 0) {
            this.getindustry();
            this.$message({
              title: "通知",
              duration: 1500,
              message: "板块资金流已更新。",
              type: "success",
              showClose: false,
            });
          } else if (msg.data.indexOf("newstock") >= 0) {
            this.getnewstock();
            this.$message({
              title: "通知",
              message: "新股日历已更新。",
              duration: 1500,
              showClose: false,
              type: "success",
            });
          } else if (msg.data.indexOf("news data updating") >= 0) {
            this.havenew = true;
          }
        };
        //发生了错误事件
        this.socket.onerror = function () {
          alert("websocket发生了错误");
        };
      };
    },
    scrollEvent(e) {
      let i =
        e.srcElement.offsetHeight +
        e.srcElement.scrollTop -
        e.srcElement.scrollHeight;
      if (i > -0.5) {
        console.log("触底");
        this.more();
      }
    },
    more() {
      this.newpage.pageSize += this.newpage.pernum;
      this.getnews();
    },
    induchang(i) {
      if (i == 1) {
        this.industrys.issurge = true;
      } else {
        this.industrys.issurge = false;
      }
    },
    pagechange(item, i, type) {
      if (i > 0 || item.page > 1) item.page = item.page + i;
      console.log(this.indexpage.page);
      switch (type) {
        case "index":
          this.getindex();
          break;
        case "newstock":
          this.getnewstock();
          break;
        default:
          break;
      }
    },
    //时间过滤加0
    appendZero(obj) {
      if (obj < 10) {
        return "0" + obj;
      } else {
        return obj;
      }
    },
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
    }
    window.removeEventListener('beforeunload', e => this.beforeunloadHandler(e))
  },
};
</script>
<style scoped src="../assets/css/index.css">
